<?php

/**
 * 标题含关键字加红
 * @param $title
 * @param $word
 * @return unknown_type
 */
//function getTitleHtml($title,$word){
//	$startSapnChar = "<span style='color: red;'>";
//	$endSpanChar = "</span>";
//	$html = $title ;
//	$keywordArray = explode(" ",$word);
//	foreach($keywordArray as $value) {
//		if($value !=null && $value != ""){
//			$startFindPos = 0 ;
//			$html = "" ;
//			$indexPos = stripos($title,$value,$startFindPos) ;
//			if($indexPos >-1){
//				do{
//					$html = $html.substr($title,$startFindPos,$indexPos-$startFindPos).$startSapnChar.
//						substr($title,$indexPos,strlen($value)).$endSpanChar.substr($title,$indexPos+strlen($value)) ;
//						$startFindPos = $indexPos +  strlen($value);
//				} while(($indexPos = stripos($title,$value,$startFindPos)) >-1) ;
//			}else{
//				$html = $title ;
//			} 
//			$title = $html ;
//		}
//	}
//	return $html ;
//}

/**
 * 含关键字的句子加红
 * @param $content
 * @param $word
 * @return unknown_type
 */
//function getContentHtml($content,$word){
//	$html = $content ;
//	return $html ;
//}


$game_sites = array('4399'=>1, '7k7k'=>2, 'game'=>3, 'kaixin001'=>4, 'android'=>5, '17173'=>6, 'app111'=>7, 'cnzz'=>8,
					'4399.com'=>1, '7k7k.com'=>2, 'game.com'=>3, 'kaixin001.com'=>4, 'android.com'=>5, '17173.com'=>6, 'app111.com'=>7, 'cnzz.com'=>8);

/**
 * 处理搜索关键字，如其中含有游戏网站，返回该网站对应的过滤号
 * 
 */
function keywordConSite($keyword){
	global $game_sites;
	$site = false;
	$strs = explode(' ',$keyword);
	foreach ($strs as $str){
		foreach ($game_sites as $key=>$game_site){
			if($key == $str){
				$site[] = $game_site;
				$str = '';
				break;
			}
		}
	}
	$keyword = implode('',$strs);
	return $site;
}

/**
 * 截取字符串（中文算1个长度）
 * @param $str
 * @param $lenth
 * @param $start
 * @return unknown_type
 */
function subString_UTF8($str, $lenth, $start=0){  
	$len = strlen($str);  
	$r = array();  
	$n = 0;  
	$m = 0;  
	for($i = 0; $i < $len; $i++) {  
		$x = substr($str, $i, 1);  
		$a  = base_convert(ord($x), 10, 2);  
		$a = substr('00000000'.$a, -8);  
		if ($n < $start){  
			if (substr($a, 0, 1) == 0) {  
			}elseif (substr($a, 0, 3) == 110) {  
				$i += 1;  
			}elseif (substr($a, 0, 4) == 1110) {  
				$i += 2;  
			}  
			$n++;  
		}else{  
			if (substr($a, 0, 1) == 0) {  
				$r[ ] = substr($str, $i, 1);  
			}elseif (substr($a, 0, 3) == 110) {  
				$r[ ] = substr($str, $i, 2);  
				$i += 1;  
			}elseif (substr($a, 0, 4) == 1110) {  
				$r[ ] = substr($str, $i, 3);  
				$i += 2;  
           	}else{  
            	$r[ ] = '';  
            }  
            if (++$m >= $lenth){  
            	break;  
            }  
       	}  
	}  
    return join('',$r); 
} 
	
	
/**
 * 句子的关键字高亮显示
 * @param $str
 * @param $words
 * @return unknown_type
 */
function highlight_word($str, $words){
	if(is_array($words)) {          
		foreach($words as $k => $word){    
         	$pattern[$k] = '/(?!<[^>]*)'.
				'('.$word.')'.
				'(?![^<]*>)/ui';   
        	$replace[$k] = "<span>\\1</span>"; 
        }    
    } else {    
       	$pattern =  '/(?!<[^>]*)'.
				'('.$word.')'.
				'(?![^<]*>)/ui';
     	$replace = "<span>\\1</span>";  
    }        
	return preg_replace($pattern,$replace,$str);  
}

/**
 * 含有关键字的句子高亮显示
 * @param $str
 * @param $words
 * @return unknown_type
 */
function highlight_words($str, $words) 
{    
	$special = ",|.|，|。|;|；|?";
	if(is_array($words)) {          
		foreach($words as $k => $word){    
         	$pattern[$k] = '/(?!<[^>]*)'.
				'(['.$special.']?[\s\x{4e00}-\x{9fa5}\w]*'.$word.'[\s\x{4e00}-\x{9fa5}\w]*['.$special.']?)'.
				'(?![^<]*>)/ui';   
        	$replace[$k] = "<font style='color:red'>\\1</font>"; 
        }    
    } else {    
       	$pattern =  '/(?!<[^>]*)'.
				'(['.$special.']?[\s\x{4e00}-\x{9fa5}\w]*'.$word.'[\s\x{4e00}-\x{9fa5}\w]*['.$special.']?)'.
				'(?![^<]*>)/ui'; 
    }        
	return preg_replace($pattern,$replace,$str);    
//	$replace = "<font style='color:red'>\\1</font>";
//	$pattern='/(?!<[^>]*)'.
//		'(['.$special.']?[\s\x{4e00}-\x{9fa5}\w]*'.$words.'[\s\x{4e00}-\x{9fa5}\w]*['.$special.']?)'.
//		'(?![^<]*>)/u';
//	return preg_replace($pattern,$replace,$str);
}


//全局参数()；
	$pageSize = 10 ;
	$pageModel= 10 ; //不允许改变的值
	$selfPageLink = "/" ; //自身链接；
	$autoLink = "" ;
	$siteurl = get_bloginfo('template_url');

	
//父类型参数（找出子类型参数）
	$cat = $_POST['cat'] ; 
	if($cat == null || "" == $cat){
		$cat = $_GET['cat'] ;
	}
	//$categories = "" ;
	//$catStr = "" ;
	if($cat != null && "" != $cat){
		$category_id = get_cat_ID($cat);
		//$categories = get_categories ('child_of='.$category_id) ;
		//$categories = $wpdb->get_results("select p.name,p.term_id as  pterm_id ,t.name,t.term_id as term_id ".
		//	" from wp_terms t ,wp_term_taxonomy m , wp_terms p ".
		//	" where t.term_id = m.term_id and p.term_id = m.parent and p.term_id  ='".$category_id."'") ;
		//foreach ($categories as $category) {
		//	$catStr =$catStr."'".$category->term_id."'," ;
		//}
	}
//关键字参数
	$keyword = $_POST['s'] ;
	if($keyword == null || "" == $keyword ){
		$keyword = $_GET["s"]; 
	}
	
	
	$site = false;
	$strs = explode(' ',$keyword);
	$ks = array();
	foreach ($strs as $k=>$str){
		foreach ($game_sites as $key=>$game_site){
			if($key == $str){
				$site[] = $game_site;
				$ks[] = $k;
				break;
			}
		}
	}
	foreach ($ks as $k){
		$strs[$k] = '';
	}
	
	$keyword1 = implode('',$strs);
	
	//将关键字中的多余空格删除
	if($keyword==null){
		$keyword = "" ;
	}
	
	$keyword = trim($keyword) ;
	keywordStat($keyword) ;
	$keyword = preg_replace("/\s+/" ," "  ,$keyword) ;
//页码参数	
	$paged = $_POST["paged"]; 
	if($paged == null || "" == $paged ){
		$paged = $_GET["paged"]; 
		if($paged == null || "" == $paged ){
			$paged = 0 ;
		}
	}
	$statNum = $pageSize * $paged ;

//使用sphinx
	require 'sphinxapi.php';
	//////////调用sphinx来取得数据///////////////
	$cl = new SphinxClient ();
	$cl->SetServer ( 'localhost', 9312);
	$cl->SetConnectTimeout ( 3 );
	//$catArray = array() ;
	//$catArray[0] = $cat ;
	if($category_id != null && "" != $category_id){
		$catArray = array() ;
		$catArray[0] = $category_id ;
		$cl->setFilter("post_category_id",$catArray);
	}
	if($site){
		$cl->setFilter('game_site', $site);
	}
	
	$cl->SetArrayResult ( true );
	$cl->SetMatchMode ( SPH_MATCH_ANY);
	$cl->SetLimits ( $statNum, $pageSize ,5000);
	$cl->SetFieldWeights(array("post_title"=>1000, "post_content"=>1));
	//$cl->SetSelect("*") ;
	$cl->SetSortMode ( SPH_SORT_EXTENDED, "@relevance DESC, post_pi DESC" );
	$res = $cl->Query ( $keyword1, "*" );
	$opts = array(
 		'before_match' => '<span style="color:red">',
 		'after_match'  => '</span>',
 		'chunk_separator' => '...'//,
		//'limit'=>300
	);
	
	////////调用sphinx来取得数据///////////////

//要显示的post的id集
	$unionSql = "" ;
	//$postids = '';
	if($res['matches'] !=null && count($res['matches'])>0){
		foreach($res['matches'] as $postidsArray){
			//$postids .= $postidsArray['id'].",";
			$unionSql = $unionSql." select ".$postidsArray['id']." as postid ,".$postidsArray['weight']." as weight  from dual  union all ";
		}
	}
	//$postids = substr($postids, 0, strlen($postids)-1);

//查询部分
	//$postQue =  "select ID,post_title, post_content,post_game_url,post_game_image,post_category_name from wp_posts where ID in (".$postids.")";
	$postQue = "" ;
	if(""==$unionSql){
		$postQue =  "select ID,post_title, post_content,post_game_url,post_game_image,post_category_name from wp_posts where 1!=1 " ;
	}else {
		$unionSql = substr($unionSql,0,strlen($unionSql)-11) ;
		$postQue = "select post.ID,post.post_title, post.post_content,post.post_game_url,post.post_game_image,post.post_category_name from wp_posts post, ".
			"(".$unionSql.") temp where  temp.postid = post.ID  " ;
	}
	$myposts = $wpdb->get_results($postQue);

//头部模板
	get_header();
?>
	<!-- 左导航开始 -->
	<div id="list_left">
		<ul>
			<li id="xuanzhong">>快速分类</li>
				<?php if($category_id != null && "" != $category_id){ ?>
					<li class="fenleileftfloat NOxuanzhong" ><a href="<?php echo $selfPageLink."?s=".$keyword ;?>">全部游戏</a></li>
				<?php }else{ ?>
					<li id="xuanzhong" class="fenleileftfloat"><a href="<?php echo $selfPageLink."?s=".$keyword ;?>">全部游戏</a></li>
				<?php } if($category_id == "6"){ ?>
					<li id="xuanzhong" class="fenleileftfloat"><a href="<?php echo $selfPageLink."?s=".$keyword."&cat=Flash小游戏" ;?>" >Flash小游戏</a></li>
				<?php }else{?>
					<li class="fenleileftfloat NOxuanzhong"><a href="<?php echo $selfPageLink."?s=".$keyword."&cat=Flash小游戏" ;?>" >Flash小游戏</a></li>
				<?php } if($category_id == "7"){ ?>
					<li id="xuanzhong" class="fenleileftfloat"><a href="<?php echo $selfPageLink."?s=".$keyword."&cat=网页游戏" ;?>" >网页游戏</a></li>
				<?php }else{?>
					<li class="fenleileftfloat NOxuanzhong"><a href="<?php echo $selfPageLink."?s=".$keyword."&cat=网页游戏" ;?>" >网页游戏</a></li>
				<?php } if($category_id == "8"){ ?>
					<li id="xuanzhong" class="fenleileftfloat"><a href="<?php echo $selfPageLink."?s=".$keyword."&cat=手机游戏" ;?>" >手机游戏</a></li>
				<?php }else{?>
					<li class="fenleileftfloat NOxuanzhong"><a href="<?php echo $selfPageLink."?s=".$keyword."&cat=手机游戏" ;?>" >手机游戏</a></li>
				<?php }?>
			</ul>
	</div>
	<!-- 左导航结束 -->
	
	<!-- 搜索结果页展示开始（包括分页） -->
	<div id="list_center">
		<!-- 列表头部信息开始 -->
		<!-- <span id="mianbaoxie" class="list_centtopspan">当前位置：<a href="?">首页</a>=><a href="<?php //echo $selfPageLink ;?>">游戏搜索</a></span> -->
		<span id="soso_result" class="list_centtopspan">&nbsp;&nbsp;&nbsp;&nbsp;找到<?php echo $res['total_found']; ?></>个相关游戏     搜索用时:"<?php echo $res['time']?>"  </span>
		<!-- 列表头部信息结束 -->	
		
		<!-- 列标体开始 -->
		<?php
		$keyArray = explode(" ",$keyword) ;
		//$contentArray = array() ;
		if($myposts != null && count($myposts)>0){
			foreach($myposts as $mypost) {
				$gamePic = $mypost->post_game_image;
				$gameLink =  $mypost->post_game_url;
				$postLink = get_permalink($mypost->ID);
				$postTitle = $mypost->post_title ; 
				$titleHtml = highlight_word($postTitle,$keyArray) ;
				$desContent = $mypost->post_content ;
				$desHtml = highlight_word(subString_UTF8($desContent,150),$keyArray) ;
				//$contentArray[] = $desContent ;
				$cat_name = $mypost->post_category_name ;
				$loadUrl = $siteurl."/images/load.gif";
				$delayImgId= "delayId".$mypost->ID ;
			?>
				<!-- add by shiwei 2011-12-07 delay img print -->
				<script type="text/javascript"> 
				delayImagPrint.put("<?php echo $delayImgId;?>","<?php echo $gamePic;?>") ;
				</script>
				<!-- add end by shiwei -->
				<div class="list">
					<span class="list_img" style="text-align: center;"><a href="<?php echo $postLink; ?>">
						<img id="<?php echo $delayImgId;?>" src="<?php echo $loadUrl ?>" width="50" height="50" style="padding-top:12px;" onerror="this.src='<?php echo $siteurl?>/images/onerror.jpg'"  alt="<?php echo $titleHtml; ?>" title="<?php echo $titleHtml; ?>" />
					</a></span>
					<h3 class="list_title"><a href="<?php echo $postLink; ?>"><?php echo $titleHtml;//$mypost->post_title; ?></a></h3>
					<span class="list_cat">
						<?php 
						if($cat_name == 'andriod' ||$cat_name == 'iphone' || $cat_name == 'windows phone' ){
							echo "游戏平台:";
					  	}else {
					 		echo "类别:";
					   	}
						?>
					<samp><?php echo $cat_name?></samp></span>
					<p class="list_neirong"><?php echo $desHtml.'... ...'; ?></p>
					<span class="list_add"><samp><?php echo $gameLink; ?></samp></span>	
					
				</div>		
		<?php 
			}
		}
	
		?>
		<!-- 列表体结束 -->
			
			
		<!--  分页开始 -->
		<!--  分页结束 -->
		
		<!-- 分页2011-12-08开始  -->
		<!-- -->
		<div id="scroll">
		<?php 	
			$MAX_PAGE = 500 ;
			$PAGE_LENGTH = 12 ;
			$PAGE_MID_HALF_LENGTH = 2 ;
			$SPECIAL = "..." ;
			$indexPage = array() ;
			
			$totalPage = ceil($res['total_found']/$pageSize) ;
			if($totalPage > $MAX_PAGE){
				$totalPage = $MAX_PAGE;
			}
			
			if($totalPage >0){
				if($paged<0){
					$paged = 0 ;
				}
				if($paged >= $totalPage){
					$paged = $totalPage-1 ;
				}
				
				$pagedLink = $selfPageLink."?s=".$keyword."&cat=".$cat;
				//上一页
				if(intval($paged) > 0 ){		
		?>
					<a href="<?php echo $pagedLink."&paged=".(intval($paged)-1); ?>" ><img src="<?php echo $siteurl ?>/images/next-top.gif" alt="上一页" title="上一页" class="f_l"/></a>
		<?php 
				}
				if($totalPage <= $PAGE_LENGTH){
					for($index = 0;$index < $totalPage ; $index ++){
						$indexPage[$index] = $index +1 ;
					}
				}else{
					/**
					 * 初始化分页数组
					 */
					$mid_index = 0 ;
					if($paged <$totalPage/2){
						//当前页在前部分
						$mid_index= $PAGE_LENGTH/2 ;
						$indexPage[$mid_index] = $mid_index +1 ;
					}else{
						//当前页在后部分
						$mid_index = $PAGE_LENGTH/2 -1;
						$indexPage[$mid_index] = $totalPage -$mid_index -1 ;
					}
					//初始化分页数组
					for($index = 0 ; $index <$mid_index ;$index ++){
						$indexPage[$index] = $index +1 ;
					}					
					for($index = 0 ; $index <$PAGE_LENGTH -$mid_index -1 ;$index ++){
						$indexPage[$PAGE_LENGTH-1-$index] = $totalPage - $index ;
					}
					/**
					 * 分析处理
					 */
					//前一半
					if($paged <$totalPage/2){
						if($indexPage[$mid_index] >= $paged +1){
							$indexPage[$mid_index + 1] = $mid_index +2 ;
							$indexPage[$mid_index + 2] = $SPECIAL ;
						}else {
							$indexPage[$mid_index - $PAGE_MID_HALF_LENGTH -1 ] = $SPECIAL ;
							$indexPage[$mid_index + $PAGE_MID_HALF_LENGTH +1 ] = $SPECIAL ;
							for($index = 0 ; $index <= 2*$PAGE_MID_HALF_LENGTH ; $index ++){
								$indexPage[$mid_index - $PAGE_MID_HALF_LENGTH +$index] = $paged+1-$PAGE_MID_HALF_LENGTH+$index  ;
							}
						}
					}else{
						//后一半
						if($indexPage[$mid_index] <= $paged+1){
							$indexPage[$mid_index-1] = $indexPage[$mid_index] -1 ;
							$indexPage[$mid_index-2] = $SPECIAL;
						}else {
							$indexPage[$mid_index - $PAGE_MID_HALF_LENGTH -1 ] = $SPECIAL ;
							$indexPage[$mid_index + $PAGE_MID_HALF_LENGTH +1 ] = $SPECIAL ;
							for($index = 0 ; $index <= 2*$PAGE_MID_HALF_LENGTH ; $index ++){
								$indexPage[$mid_index - $PAGE_MID_HALF_LENGTH +$index] = $paged+1-$PAGE_MID_HALF_LENGTH+$index  ;
							}
						}
					}
					
				}
				//输出HMTL
				for($index = 0; $index < count($indexPage); $index++ ){
					if($indexPage[$index] == $paged+1){
		?>
						<font class="linknone"><?php echo $indexPage[$index];?></font>
		<?php 				
					}elseif ($indexPage[$index] == $SPECIAL) {
		?>
						<a class="linkstyle03"><?php echo $SPECIAL;?></a>
		<?php 				
					}else {
		?>
						<a href="<?php echo $pagedLink."&paged=".($indexPage[$index]-1); ?>" class="linkstyle03"><?php echo $indexPage[$index];?></a>
		<?php 				
					}
				}
				//下一页
				if(intval($paged)<$totalPage-1){
		?>
					<a href="<?php echo $pagedLink."&paged=".(intval($paged)+1); ?>" ><img src="<?php echo $siteurl ?>/images/next-bottom.gif" alt="下一页" title="下一页" class="f_l" /></a>
		<?php 
				}
			}
		?>
						
		</div>
		<!-- -->
	
	</div>
	<!-- 搜索结果页展示结束（包括分页） -->
	
	<!-- 热门游戏开始 -->
	<div id="list_right">
		<h2>热门游戏推荐</h2>
	</div>
	<!-- 热门游戏结束 -->
	

</div>
<?php
//尾部模板 
	get_footer();
?>